package com.haier.npt.sso.authentication;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.util.Assert;

import com.haier.npt.sso.authentication.cache.CacheHelper;
import com.haier.npt.sso.authentication.cache.TokenCacheService;
import com.haier.npt.sso.domain.SysUserWapper;
import com.haier.npt.sso.i18n.SSOMessageCode;
import com.haier.npt.sso.oauth.OauthService;
import com.haier.npt.utils.MessageHelper;


/**
 * 
 * @author lixu
 *
 */
public class PreAuthenticationUserDetailsService
		implements AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> ,InitializingBean {


	@Autowired
	private OauthService oauthService ; 
	
	@Autowired
	private TokenCacheService  tokenCacheService ;  
	@Autowired
	private MessageHelper messageHelper;


	@Override
	public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token) throws UsernameNotFoundException {
		//从缓存中取用户信息
		SysUserWapper  userWapper = this.tokenCacheService.getLoginUserFromCache(token.getName()) ; 
		//缓存中取用户信息
		if(userWapper!=null){
			CacheHelper.set(true);
			return userWapper ; 
		}else{
			//缓存中没有 
			//根据token 获取用户信息
			Object sysUser =oauthService.getUserObject(token.getName()); 
			if(sysUser==null){
				throw new UsernameNotFoundException(
						messageHelper.getMessage(SSOMessageCode.FETCH_USER_INGO_ERROR));//"获取用户信息失败"
			}
            CacheHelper.set(false); //标记未缓存			
			SysUserWapper sysUserWapper = new SysUserWapper(sysUser,token.getName());
			return sysUserWapper ; 
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.notNull(oauthService, "An oauthService must  not null ");
	}
	
}
